define(function(require, exports, module) {
    var myPub = require('./public');
    var priceCount = require('./submit_calcLastPrice');
    // var couponPlat = require('./submit_coupon_business');


    /***************************    兑换优惠劵     ******************************/

    var oGiftMaTxt = $('.js_giftMaTxt');
    var oGiftMa_TipTxt = $('.js_giftMa_tipTxt');
    var oSubmitGiftMa = $('.js_submitGiftMa');
    var $couponList = $('.js_couponList');

    var oClearBtn = $('.js_clearBtn');

    var offTap = true;                  // 阻止多次点击
    var moreTapOffTime = null;          // 多次点击定时器
    var Testing = false;                // 校验按钮是否可点击
    var maxLength = 6;                 // 校验输入框的最长内容

    var errorTip = ['年丰大当家优惠券使用说明', '<span class="color_red">优惠劵编号错误，请重新输入</span>'];
    var layerTip = ['在使用优惠劵之前需要绑定您的手机号', '恭喜您，验证通过!'];
    var layerStyle_black = 'background-color:rgba(0,0,0, 0.6); color:#FFFFFF; border:none; border-radius: 5px; min-width: 50%;';

    var resizeTimer = null;

    // 表单验证
    oGiftMaTxt.on('input propertychange',function() {
        // 通过前端验证 修改提示和改变检测状态
        ValiNumLetter(oGiftMaTxt, function () {
            Testing = false;
            oGiftMa_TipTxt.html(errorTip[1]);
        }, function () {
            Testing = true;
            oGiftMa_TipTxt.html(errorTip[0]);
        });

        // 满足指定数字个数开始验证
        if(oGiftMaTxt.val().length >= maxLength) {
            Testing ? oSubmitGiftMa.addClass('active') : oSubmitGiftMa.removeClass('active');
        }
        else {
            oSubmitGiftMa.removeClass('active');
        }
    });

    // 提交按钮操作
    oSubmitGiftMa.hammer().on('tap', function () {
        // 变亮状态 还有active
        if($(this).hasClass('active')) {
            // 防止多次点击
            if(offTap) {
                oGiftMaTxt.blur();
                offTap = false;
                exchangeCouponWithPay();
                // 绑定成功提示
                // myPub.TipLayer_noShade(layerTip[1], layerStyle_black);
            }
            clearTimeout(moreTapOffTime);
            moreTapOffTime = setTimeout(function () {
                offTap = true;
            }, 500);
        }
    });

    function exchangeCouponWithPay() {
        var codeSign = oGiftMaTxt.val();
        var allProduct = priceCount.calAllProduct();
        G_JSON_POST("/coupon/exchangeCoupon",{
            codeSign:codeSign,
            productsJson:JSON.stringify(allProduct)
        },function (data) {
            if(data.status != "success"){
                myPub.TipLayer(data.message);
            }else{
                var couponArray = data.obj;
                for(var i=0;i<couponArray.length;i++){
                    var coupon = couponArray[i];
                    addCanUseCoupon(coupon);
                    // couponPlat.GetGoodsList();
                    myPub.TipLayer('兑换成功');
                }
                oGiftMaTxt.val('');
            }
        });
    }
    exports.exchangeCouponWithPay = exchangeCouponWithPay;
    function addCanUseCoupon(coupon) {
        var benginDate = new Date(coupon.beginDate);
        var endDate = new Date(coupon.endDate);
        var couponHtml = [
            '<div class="coupon platCoupon orderCoupon js_coupon" '
            +'  data-couponId="'+coupon.userCouponId+'"'
            +'  data-supplierId="'+coupon.supplierId+'"'
            +'  data-limitType="'+coupon.limitType+'"'
            +'  data-supplierSet="'+coupon.supplierSet+'"'
            +'  data-categorySet="'+coupon.categorySet+'"'
            +'  data-goodsSet="'+coupon.goodsSet+'">'
            +'      <div class="couponBox" >'
            +'          <div class="couponInfo HBox">'
            +'              <div class="couponInfoLeft HBox BoxCenter">'
            +'                 <div class="couponPrice">'
            +'                      <em>￥</em>'
            +'                      <span class="js_costPrice">' + coupon.costPrice + '</span>'
            +'                      <p>满<i class="js_threshold">' + coupon.needPrice + '</i>元可用</p>'
            +'                  </div>'
            +'              </div>'
            +'              <div class="couponInfoCenter Bflex1 height_100">'
            +'                  <div class="couponUseType">'
            +'                      <h5 class="singleLine" >' + coupon.couponName + '</h5>'
            +'                      <div class="tip_use" >'
            +'                          <p>' + coupon.limitDescribe + '</p>'
            +'                      </div>'
            +'                      <div class="tip_useLimt Bflex1">'
            +'                          <p>' + myPub.FormatDateTime(benginDate,"minDay",".") + ' - ' + myPub.FormatDateTime(endDate,"minDay",".") + '</p>'
            +'                      </div>'
            +'                  </div>'
            +'              </div>'
            +'              <div class="couponInfoRight HBox BoxCenter">'
            +'                  <div class="useThisCoupon">'
            +'                      <div class="useThisCouponBtn HBox BoxCenter">'
            +'                          <p class="activeCheck">'
            +'                              <span class="icon-check"></span>'
            +'                          </p>'
            +'                      </div>'
            +'                  </div>'
            +'              </div>'
            +'          </div>'
            +'      </div>'
            +'      <div class="gapBox gapBox_right">'
            +'          <span class="gap gap_top"></span>'
            +'          <span class="gap_line"></span>'
            +'          <span class="gap gap_bot"></span>'
            +'      </div>'
            +'  </div>'].join("");
        $couponList.append(couponHtml);
    }

    // 清空按钮操作
    oClearBtn.hammer().on('tap', function () {
        oGiftMaTxt.val('');
        oGiftMa_TipTxt.html(errorTip[0]);
        oSubmitGiftMa.removeClass('active');
    });

    /* 数字字母验证 */
    function ValiNumLetter(obj,fn1,fn2) {
        var reg = new RegExp("^[a-zA-Z0-9]*$");
        if(!reg.test(obj.val())){
            if(fn1) fn1();
        }
        else{if(fn2) fn2();}
    }



    /***************************    使用优惠劵     ******************************/

    var oShadow = $('.js_shadow');				            // 阴影
    var oCouponSeletSide = $('.js_couponSeletSide');        // 优惠劵弹框
    var oUseCouponSubOrd = $('.js_useCouponSubOrd');        // 优惠劵列表展示按钮
    var oSubOrdCoupon = $('.js_subOrdCoupon');              // 提交订单 优惠劵框
    var oCouponBtn_close = $('.js_couponBtn_close');        // 优惠劵关闭
    var bSideOff = true;
    var moveHeight = oCouponSeletSide.outerHeight(true);    // 优惠劵弹框高度
    oCouponSeletSide.css({'bottom': -moveHeight });

    // 提交订单选 优惠劵
    oUseCouponSubOrd.hammer().on('tap', function () {
        if ($(this).find('.couponOff').length > 0){
            return;
        }
        if(typeof bindMobile != "undefined" && bindMobile == "bindMobile"){
            // 没有绑定的话 弹出 绑定手机弹框
            myPub.askLayer(layerTip[0], function () {
                // 立即绑定
                if(typeof backHref != "undefined"){
                    window.location.href = "/h/login/bindMobile?backHref=" + backHref;
                }else {
                    window.location.href = "/h/login/bindMobile";
                }
                myPub.LayerCloseAll();
            }, function () {
                // 取消
                myPub.LayerCloseAll();
            }, 'no', null, ['立即绑定','取消']);
            return;
        }
        if(!bSideOff)  return;
        bSideOff = false;
        oSubOrdCoupon.show().stop().animate({ 'bottom':0 },300,function() {
            oShadow.show();
            bSideOff = true;
        });
        myPub.HamstopPropaga();
    });


    // 优惠劵使用选择
    $couponList.hammer().on('tap', function (e) {
        var _tag = e.gesture.target;
        var $target;
        if($(_tag).parents('.js_coupon').length > 0) {
            $target = $(_tag).parents('.js_coupon');
        }
        else {
            return
        }
        if($target.hasClass('active')) {
            // 取消使用优惠券
            oSubOrdCoupon.find('.js_coupon').removeClass('active');
            var overMid = $('.js_showBusCoup ');
            if(overMid.length > 0){
                $('.js_toUseCouponNull').hide();
                $('.js_toUseCouponHave').show().find('.js_verMid').text(overMid.length+'张可用');
                $('.js_showUseCouponPrice').hide().find('.js_showPrice').text('0.0');
            }
           // $('.js_toUseCoupon').show();
            priceCount.useCouponPrice(0,0);
        } else {
            // 使用优惠券
            oSubOrdCoupon.find('.js_coupon').removeClass('active');
            $target.addClass('active');//设置选中
            var couponPrice = $target.find('.js_costPrice').text();                        // 获取优惠卷金额
            var couponId = parseInt($target.attr("data-couponId"));                        // 获取优惠卷id
            $('.js_showUseCouponPrice').show().find('.js_showPrice').text(couponPrice);    // 将金额放进优惠卷位置
           // $('.js_toUseCoupon').hide();// 隐藏对应的
            $('.js_toUseCouponNull').hide();
            $('.js_toUseCouponHave').hide();
            priceCount.useCouponPrice(parseFloat(couponPrice),couponId);
            //优惠券三期
            // selected($target);
        }
        myPub.HamstopPropaga();
    });

    // 默认选中最大额的优惠券并给显示的优惠券添加类名标识
    function couponchooseShow(arr, fn1) {
        // console.log('arr',arr)
        if(oUseCouponSubOrd.length > 0){
            var w =  $("div.js_couponList > div.js_coupon");
            if (w.length > 0) {
                if(arr.length > 0){
                    for(var o = 0;o < arr.length;o++){
                        var arrDepare = arr[o];
                        for(var j = 0;j < arrDepare.length;j++){
                            var nCompare = arrDepare[j].oldPrice*1 - arrDepare[j].BusConPrice*1;
                            if(nCompare >= arrDepare[j].limitPlatPrice*1){
                                IsShow(w,arrDepare[j].couponId,'add')
                            }else{
                                IsShow(w,arrDepare[j].couponId,'remove')
                            }
                        }
                    }
                }
                initCoupon();
            }
        }
        if(fn1)fn1();
    }

    exports.couponchooseShow = couponchooseShow;

    function initCoupon() {
        var w =  $("div.js_couponList > div.js_showBusCoup");
        if(w.length == 0){
            $('.js_toUseCouponNull').show();
            $('.js_toUseCouponHave').hide();
            $('.js_showUseCouponPrice').hide();
            priceCount.useCouponPrice(parseFloat(0), 0);
        }
        if (w.length > 0) {

            var max = w.eq(0).find('.js_costPrice').text()*1;
            var index = 0;
            for(var i=1;i<w.length;i++){
                if( w.eq(i).find('.js_costPrice').text()*1 > max ){
                    max = w.eq(i).find('.js_costPrice').text();
                    index = i;
                }
            }

            w = w.eq(index);
            selected(w);
        }

    }
    exports.initCoupon = initCoupon;



    function selected(w) {
        w.siblings().removeClass('active');
        w.addClass('active');
        var couponPrice = w.find('.js_costPrice').text();
        var couponId = parseInt(w.attr("data-couponId"));
        // $('.js_showUseCouponPrice').show().find('.js_showPrice').text(couponPrice);
        // $('.js_toUseCoupon').hide();
        $('.js_showUseCouponPrice').show().find('.js_showPrice').text(couponPrice);
        $('.js_toUseCouponNull').hide();
        $('.js_toUseCouponHave').hide();
        priceCount.useCouponPrice(parseFloat(couponPrice), couponId);
    }


    function IsShow(duty,upon,type) {
        for(var i = 0;i < duty.length;i++){
            var nPlatCouponId = duty.eq(i).attr('data-couponid')*1;
            if(upon == nPlatCouponId){
                if(type == 'remove'){
                    duty.eq(i).removeClass('js_showBusCoup')
                }else if(type == 'add'){
                    duty.eq(i).addClass('js_showBusCoup')
                }
            }

            if(duty.eq(i).hasClass('js_showBusCoup')){
                duty.eq(i).show();
            }else{
                duty.eq(i).hide();
            }
        }
    }

    // 阴影关闭
    oShadow.hammer().on('tap', function (e) {
        //隐藏服务
        oSubOrdCoupon.stop().animate({bottom:-moveHeight},300,function(){
            oSubOrdCoupon.hide();
            oShadow.hide();
            bSideOff = true
        });
        e.stopPropagation();
        // console.log(" bbb ");
    });


    // 不使用优惠劵
    oCouponBtn_close.hammer().on('tap', function (e) {
        // 隐藏弹框
        oSubOrdCoupon.stop().animate({bottom:-moveHeight},300,function(){
            oSubOrdCoupon.hide();
            oShadow.hide();
            bSideOff = true
        });
        e.stopPropagation();
    });

});